package cn.tianyigps.tianyigpsapiv2.controller;

import cn.tianyigps.tianyigpsapiv2.param.dto.EquipmentDTO;
import cn.tianyigps.tianyigpsapiv2.param.enums.ResponseEnum;
import cn.tianyigps.tianyigpsapiv2.param.vo.ResponseVo;
import cn.tianyigps.tianyigpsapiv2.service.EquipmentService;
import cn.tianyigps.tianyigpsapiv2.utils.TimeUtil;
import cn.tianyigps.tianyigpspublic.bean.EquipmentHistory;
import cn.tianyigps.tianyigpspublic.bean.EquipmentLastData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @Author: LiuHao
 * @Descirption:
 * @Date: 2019/4/19_13:59
 */
@Slf4j
@RestController
@RequestMapping("/equipment")
@CrossOrigin
@Api(value = "EquipmentController", description = "设备查询接口")
public class EquipmentController {


    @Autowired
    private EquipmentService equipmentService;

    /**
     * 实时记录
     * @return
     */
    @GetMapping
    @ApiOperation(value = "设备实时记录查询", notes = "测试接口")
    public ResponseVo latestData(@RequestParam String equipmentId, @RequestParam(required = false) String mapType){
        EquipmentLastData equipmentLastData = equipmentService.lastData(equipmentId,mapType);
        if(equipmentLastData == null){
            return ResponseVo.notFoundRequest("查询数据未找到");
        }
        return ResponseVo.response(ResponseEnum.QUERY_SUCCESS,equipmentLastData);
    }

    /**
     * 根据日期分表,按天查询定位历史记录（轨迹）
     * @param equipmentDTO
     * @return
     */
    @GetMapping("/locus")
    @ApiOperation(value = "设备轨迹查询", notes = "测试接口")
    public ResponseVo locus(EquipmentDTO equipmentDTO){
        if(StringUtils.isEmpty(equipmentDTO.getEquipmentId())){
            return ResponseVo.badRequest("设备ID不能为空！");
        }
        if(equipmentDTO.getStart()==null && equipmentDTO.getEnd()==null){
            return ResponseVo.badRequest("起止时间至少填一个！");
        }
        if(equipmentDTO.getStart() == null){
            equipmentDTO.setStart(new Date());
        }
        if(equipmentDTO.getEnd() == null){
            equipmentDTO.setEnd(new Date());
        }
        List<String> days = TimeUtil.getDiffDays(equipmentDTO.getStart(), equipmentDTO.getEnd());
        if(days.size()>62){
            return ResponseVo.badRequest("查询天数不能超过两个月！");
        }
        try{
            List<EquipmentHistory> list = equipmentService.locus(equipmentDTO);
            if(CollectionUtils.isEmpty(list)){
                return ResponseVo.response(ResponseEnum.QUERY_NULL);
            }
            return ResponseVo.response(ResponseEnum.SUCCESS,list);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return ResponseVo.response(ResponseEnum.ERROR);
        }

    }

}
